<template>
	<view class="publish">
		<post-nav-bar title="创作帖子"></post-nav-bar>
		<view class="cover-box">
			<view class="cover-blank" v-if="cover_img == ''" @click="cover_select">
				<uni-icons type="camera-filled" size="80" color="#999"></uni-icons>
				<view>点击上传封面图片</view>
			</view>
			<view class="cover-img" v-else>
				<image :src="cover_img" mode="aspectFill"></image>
				<button class="change-cover" @click="cover_select">更换图片</button>
			</view>
			<view class="tip" v-if="tip.image !== ''">{{tip.image}}</view>
		</view>
		<view class="wrap">
			
			<view class="name-box">
				<input class="name" type="text" v-model="post.name" placeholder="输入菜品名称"/>
				<view class="tip" v-if="tip.name !== ''">{{tip.name}}</view>
			</view>
			
			<view class="tag-box">
				<view class="sub-title">1.编辑标签</view>
				<view class="tag-display" v-if="post.category.length != 0">
					<view v-for="(tag, index) in post.category" :key="index" class="tag">{{ tag }}</view>
				</view>
				<view class="tag-create">
					<textarea class="category" v-model="tag_string" cols="50" rows="8" placeholder="输入菜品标签,用逗号分隔"></textarea>
					<button class="change-tag" @click="change_tag">应用标签</button>
				</view>
				<view class="tip" v-if="tip.category !== ''">{{tip.category}}</view>
			</view>
			
			<view class="material-box">
				<view class="sub-title">2.编辑用料</view>
				<uni-table class="material-table" border stripe :emptyText="material_list.length ? '' : '暂无更多数据'" >
					<!-- 表头行 -->
					<uni-tr>
						<uni-th width="100" align="center">材料</uni-th>
						<uni-th width="100" align="center">用量</uni-th>
						<uni-th width="100" align="center">操作</uni-th> 
					</uni-tr>
					<!-- 表格数据行 -->
					<uni-tr v-for="(item, index) in material_list" :key="index">
						<uni-td align="center">
							<input v-model="item.name" placeholder="请输入材料名称"/>
						</uni-td>
						<uni-td align="center">
							<input v-model="item.num" placeholder="请输入用量"/>
						</uni-td>
						<uni-td align="center">
					        <button class="del-row" @click="removeRow(index)">删除</button>
						</uni-td>
					</uni-tr>
				</uni-table>
				<button class="add-row" @click="addRow">添加一行</button>
				<view class="tip" v-if="tip.material !== ''">{{tip.material}}</view>
			</view>
			
			<view class="step-box">
				<view class="sub-title">3.编辑步骤</view>
				<view class="step">
					<view class="unit" v-for="(item, index) in step_list" :key="index">
						<button class="insert-unit" @click="insert_unit(index)">在此插入步骤</button>
						<view class="up">
							<view class="step-title">步骤{{index+1}}</view>
							<button class="del-unit" @click="del_unit(index)"><uni-icons type="minus-filled" size="30" color="#FF4D4F"></uni-icons></button>
						</view>
						<view class="step-img">
							<view class="img-blank" v-if="item.image == ''" @click="step_select(index)">
								<uni-icons type="camera-filled" size="80" color="#999"></uni-icons>
								<view>点击上传步骤图片，让菜谱更受欢迎</view>
							</view>
							<view class="img" v-else>
								<image :src="item.image" mode="aspectFill"></image>
								<button class="change-img" @click="step_select(index)">更换图片</button>
							</view>
						</view>
						<view class="step-content">
							<textarea class="content" v-model="item.content" cols="200" rows="8" placeholder="描述该步骤"></textarea>
						</view>
						
					</view>
					<view class="tip" v-if="tip.step !== ''">{{tip.step}}</view>
					<button class="add-unit" @click="add_unit">添加步骤</button>
				</view>				
			</view>
		</view>
		<view class="fill"></view>
		<view class="btn-box">
			<button class="post" @click="do_post">发布</button>
		</view>
	</view>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue';
import { appUrl } from '../../main';
import LoginViewVue from '../LoginView/LoginView.vue';

//令牌
const token = ref("")
//帖子结构
const post = ref({
	name:"",
	category: [],
	material: [],
	step:[],
	num:[]
})
//提交提示
const tip = ref({
	name:"",
	image: "",
	category: "",
	material: "",
	step:"",
	num:""
})

//封面图片
const cover_img = ref("")
//选择封面图片
const cover_select = () => {
	uni.chooseImage({
		count: 1, 
		sizeType: ['compressed'],
		sourceType: ['album','camera'],
		success: res => {
			cover_img.value = res.tempFilePaths[0];
			tip.value.image = ""
		}
	});
}
//菜品标签字符串
const tag_string = ref("")
//修改标签
const change_tag = () => {
	const regex = /[,，]/;
	post.value.category = tag_string.value.split(regex).map(s => s.trim());
	tip.value.category = ""
}

//用料数组
const material_list = ref([])
const addRow = () => {
  material_list.value.push({ name: '', num: '' });
  tip.value.material = ""
};
const removeRow = (index) => {
    material_list.value.splice(index, 1);
};

//步骤数组
const step_list = ref([
	{
		content: "",
		image: ""
	}
])
const step_select = (index) => {
	uni.chooseImage({
		count: 1, 
		sizeType: ['compressed'],
		sourceType: ['album','camera'],
		success: res => {
			step_list.value[index].image = res.tempFilePaths[0];			
		}
	});
}
const del_unit = (index) => {
	step_list.value.splice(index, 1)
}
const insert_unit = (index) => {
	step_list.value.splice(index, 0, { content:"",image:"" })
	tip.value.step = ""
}
const add_unit = () => {
	step_list.value.push({ content:"",image:"" })
	tip.value.step = ""
}


const validation = () => {
	tip.value.image = ""
	tip.value.name = ""
	tip.value.category = ""
	tip.value.material = ""
	tip.value.step = ""
	
	if(cover_img.value == ""){
		tip.value.image = "封面图片不能为空"
		return false
	}else if(post.value.name == ""){
		tip.value.name = "菜品名称不能为空"
		return false
	}else if(post.value.category.length == 0){
		tip.value.category = "标签不能为空"
		return false
	}else{
		if(material_list.value.length == 0){
			tip.value.material = "菜品用料不能为空"
			return false
		}else{
			for (let item of material_list.value) {
			    if (item.name == "" || item.num == "") {
					tip.value.material = "有材料未填写,请填写完整"
			        return false; 
			    }
			}
		}
		if(step_list.value.length == 0){
			tip.value.step = "制作步骤不能为空"
			return false
		}else{
			for (let item of step_list.value) {
			    if (item.content == "") {
					console.log(item.content == "");
					tip.value.step = "有步骤未填写,请填写完整"
			        return false; 
			    }
			}
		}
		return true
	}
}

let image_list = []

const do_post = () => {
	if(validation()){
		//添加封面图片
		image_list.push({ name:"cover_image",uri:cover_img.value })
		//处理菜品用料
		post.value.material = material_list.value.map(item => {
			return `${item.name}  ${item.num}`;
		});
		//处理制作步骤
		let img_num = 0;
		step_list.value.forEach((item, index) => {
			// 构建带编号的步骤描述
			post.value.step.push(`${index + 1}   ${item.content}`);
	
			// 如果image不为空，则记录序号（从1开始）
			if (item.image) {
				img_num++;
				post.value.num.push((index + 1).toString());
				image_list.push({ name: "image" + (index)  ,uri:item.image})
			}
		});
		
		console.log(image_list);
		
		uni.uploadFile({
			url: appUrl + "/dish/upload", 
			files: image_list,
			fileType: 'image',
			name: 'image',
			formData: post.value,
			header:{
				'token': token.value
			},
			success: (res) => {
				console.log(res.data.data);
				uni.showToast({
					title:"成功",
				})
			}
		});
		
		
	}else{
		uni.showToast({
			icon:"error",
			title:"信息未填写完整",
			duration: 1000
		})
	}
}

//钩子函数
onMounted(() => {
	token.value = uni.getStorageSync("token")
	if(token.value === null || token.value === ""){
		uni.showToast({
			icon:'error',
			title:"用户未登录",
			duration: 1000
		})
		uni.reLaunch({
			url:"/pages/UserView/UserView"
		})
	}
})

</script>

<style lang="scss" scoped>
.publish{
	.tip{
		width: 100%;
		height: auto;
		padding-left: 30rpx;
		color: #FF4D4F;
	}
	.cover-box{
		width: 100%;
		height: 360rpx;
		.cover-blank{
			width: 100%;
			height: 360rpx;
			background-color: #eee;
			color: #999;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}
		.cover-img{
			position: relative;
			display: inline-block; /* 确保容器只包裹内容大小 */
			width: 100%; 
			height: 360rpx;
			image {
				width: 100%;
				height: 360rpx;
				border-radius: 10rpx;
				margin-bottom: 50rpx;
			}
			.change-cover{
				position: absolute;
				width: 200rpx;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
				color: white;
				border: none;
				padding: 5px 10px;
				border-radius: 5px;
				bottom: 10rpx; /* 距离底部的距离 */
				right: 10rpx; /* 距离右侧的距离 */
				
			}
		}
		
	}
	.wrap{
		padding: 0 30rpx 0 30rpx;
		.sub-title{
			margin: 10rpx 0;
			font-size: 20px;
			color: #FF4D4F;
			font-weight: bold;
		}
		.name-box{
			margin: 10rpx 0;
			.name{
				width: 100%;
				height: 130rpx;
				font-size: 30px;
				font-weight: bold;
			}
		}
		.tag-box{
			width: 100%;
			.tag-display{
				display: flex;
				flex-wrap: wrap;
				margin-bottom: 40rpx;
				.tag {
					height: 20px;
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 10px 10px 0 0;
					padding: 0 5px;
					border-radius: 4px;
					font-size: 10px;
					color: rgb(221, 213, 158);
					background-color: rgba(221, 213, 158, 0.1);
					border: 1px solid rgb(221, 213, 158);
				}
			}
			.tag-create{
				width: 100%;
				position: relative;
				height: 250rpx;
				.category{
					box-sizing: border-box;
					border: 1px solid #aaa;
					border-radius: 10px;
					width: 100%;
					height: 250rpx;
					padding: 20rpx;
				}
				.change-tag{
					position: absolute;
					margin: 20rpx 0;
					height: 70rpx;
					display: flex;
					justify-content: center;
					font-size: 15px;
					align-items: center;
					background-color: #FF4D4F;
					color: #fff;
					bottom: 0; /* 距离底部的距离 */
					right: 20rpx; /* 距离右侧的距离 */
				}
			}
		}
		.material-box{
			margin: 30rpx 0;
			.material-table{
				margin-top: 20rpx;
			}
			.add-row{
				background-color: #fff;
				color: #aaa;
			}
			.del-row{
				background-color: #fff;
				color: #FF4D4F;
				border: 1px solid #FF4D4F;
				height: 30px;
				width: 80px;
				font-size: 15px;
				display: flex;
				justify-content: center;
				align-items: center;
				
			}
		}
		.step-box{
			.step{
				margin: 20rpx 0;
				.unit{
					width: 100%;
					padding: 20rpx;
					.up{
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
						.step-title{
							font-size: 20px;
						}
					}

					.step-img{
						width: 100%;
						height: 360rpx;
						margin: 20rpx 0;
						.img-blank{
							width: 100%;
							height: 360rpx;
							background-color: #eee;
							color: #999;
							display: flex;
							flex-direction: column;
							justify-content: center;
							align-items: center;
							border-radius: 10px;
						}
						.img{
							position: relative;
							display: inline-block; /* 确保容器只包裹内容大小 */
							width: 100%; 
							height: 360rpx;
							image {
								width: 100%;
								height: 360rpx;
								border-radius: 10rpx;
								margin-bottom: 50rpx;
							}
							.change-img{
								position: absolute;
								width: 200rpx;
								height: 80rpx;
								display: flex;
								justify-content: center;
								align-items: center;
								background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
								color: white;
								border: none;
								padding: 5px 10px;
								border-radius: 5px;
								bottom: 10rpx; /* 距离底部的距离 */
								right: 10rpx; /* 距离右侧的距离 */
							}
						}
					}
					.step-content{
						.content{
							box-sizing: border-box;
							border-radius: 10px;
							width: 100%;
							height: 200rpx;
							padding: 20rpx;
						}
					}
				}
				.del-unit{
					margin: 0;
					background-color: #fff;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
					height: 60rpx;
					width: 60rpx;
				}
				.insert-unit{
					margin: 0 20rpx;
					color: #999;
					background-color: #fff;
					border: 1px solid #999;
					height: 50rpx;
					font-size: 15px;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-bottom: 20rpx;
				}
				.add-unit{
					margin: 0 20rpx;
					color: #FF4D4F;
					background-color: #fff;
					border: 1px solid #FF4D4F;
				}
			}
		}
	}
	.fill{
		height: 300rpx;
	}
	.btn-box{
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		.post{
			background-color: #FF4D4F;
			color: #fff;
			border-radius: 0;
		}
	}
}
</style>